package org.djw.hrm.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.djw.hrm.domain.Employee;
import org.djw.hrm.domain.Login;
import org.djw.hrm.domain.MealAndLogin;
import org.djw.hrm.domain.Tenant;
import org.djw.hrm.dto.TenantRegisterDto;
import org.djw.hrm.feign.client.AuthFeignClient;
import org.djw.hrm.mapper.EmployeeMapper;
import org.djw.hrm.mapper.TenantMapper;
import org.djw.hrm.service.ITenantService;
import org.djw.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author djw
 * @since 2022-02-10
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private AuthFeignClient authFeignClient;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void entering(TenantRegisterDto dto) {
        //1.参数校验
        //1.1套餐Id是否为空
        if (dto.getMealId() == null){
            throw new RuntimeException("请选择套餐!!");
        }
        //1.2手机号和邮箱是否为空
        if (dto.getEmployee().getEmail() == null || dto.getEmployee().getTel() == null){
            throw new RuntimeException("手机号或者邮箱不能为空!!");
        }
        //1.3公司执照是否为空
        if (dto.getTenant().getCompanyNum() == null){
            throw new RuntimeException("公司信用代码不能为空!!");
        }
        //1.4公司名称是否存在
        List<Tenant> tenants = tenantMapper.loadByCompanyName(dto.getTenant().getCompanyName());
        if (tenants.size() != 0){
            throw new RuntimeException("公司名称已经存在,请重新输入!!");
        }
        //1.5用户名是否存在
        Login login = authFeignClient.getByUsername(dto.getLogin().getUsername());
        if (login != null){
            throw new RuntimeException("用户名已经存在,请重新输入!!");
        }
        //2.如果通过,保存数据,进行注册
        //2.1保存Login返回自增ID,
        AjaxResult ajaxResult = authFeignClient.save(dto.getLogin());
        Long loginId = Long.valueOf(String.valueOf(ajaxResult.getResultObj()));
        //2.2保存mealId
        MealAndLogin mealAndLogin = new MealAndLogin();
        mealAndLogin.setLogin_id(loginId);
        mealAndLogin.setMeal_id(dto.getMealId());
        authFeignClient.saveMealAndLogin(mealAndLogin);
        //将Login返回的自增ID设置给employee
        Employee employee = dto.getEmployee();
        employee.setLoginId(loginId);
        //2.3保存employee返回自增ID
        employeeMapper.insert(employee);
        Tenant tenant = dto.getTenant();
        tenant.setAdminId(employee.getId());
        //2.4保存Tenant
        tenantMapper.insert(tenant);

    }
}
